//
//  ReigsterCameraAccountController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/10/13.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "ReigsterCameraAccountController.h"
#import "openApiService.h"
#import "QRCoderViewController.h"
#import "ZTLCCameraUtil.h"
static NSString *const strSrv = @"openapi.lechange.cn";
static NSInteger const iPort = 443;
static NSString *const strAppId = @"lca1e05b18e7274569";
static NSString *const strAppSecret = @"686e76ef69534a659f62f55650c1c1";

@interface ReigsterCameraAccountController ()
@property (nonatomic, strong)UIButton      *m_btnPhone;
@property (nonatomic, strong)UITextField   *m_textPhone;
@property (nonatomic, strong)UITextField   *m_textVerifi;
@property (nonatomic, strong)UIButton      *m_btnSms;
@property (nonatomic, strong)UIView        *m_viewVerifi;
@property (nonatomic, strong)UIView        *m_viewPhone;
@property (nonatomic, assign)NSInteger     m_interval;
@property (nonatomic, strong)NSTimer       *m_timer;
@property (nonatomic, strong)UIColor       *m_btnOldColor;
@property (nonatomic, strong)UIColor       *m_btnChangeColor;
@property (nonatomic, strong)UILabel       *m_lblHint;
@property (nonatomic, strong)UIActivityIndicatorView *m_progressInd;

@end

@implementation ReigsterCameraAccountController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title  = @"绑定手机";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(sure)];
    self.m_btnOldColor = [UIColor colorWithRed:0/255 green:122.0/255 blue:255.0/255 alpha:1];
    self.m_btnChangeColor = [UIColor colorWithRed:195.0/255 green:195.0/255 blue:200.0/255 alpha:1];
    [self.view addSubview:self.m_btnPhone];
    [self.m_btnPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(kIphoneSize_Height(10));
        make.leading.equalTo(self.view);
        make.width.equalTo(kIphoneSize_Widith(55));
        make.height.equalTo(self.m_btnPhone.width);
        
    }];
    [self.view addSubview:self.m_viewPhone];
    [self.m_viewPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_btnPhone);
        make.leading.equalTo(self.m_btnPhone.trailing).offset(1);
        make.trailing.equalTo(self.view);
    }];
    [self.m_viewPhone addSubview:self.m_textPhone];
    [self.m_textPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_viewPhone);
        make.leading.equalTo(self.m_viewPhone).offset(10);
        make.trailing.equalTo(self.m_viewPhone);
        
    }];

    [self.view addSubview:self.m_btnSms];
    [self.m_btnSms mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_btnPhone.bottom).offset(1);
        make.trailing.equalTo(self.view);
        make.height.equalTo(self.m_btnPhone.height);
        make.width.equalTo(kIphoneSize_Widith(110));
        
    }];
    [self.view addSubview:self.m_viewVerifi];
    [self.m_viewVerifi mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(self.view);
        make.height.top.equalTo(self.m_btnSms);
        make.trailing.equalTo(self.m_btnSms.leading).offset(-1);
        
    }];
    [self.m_viewVerifi addSubview:self.m_textVerifi];
    [self.m_textVerifi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(20);
        make.top.bottom.trailing.equalTo(self.m_viewVerifi);
    }];
    [self.view addSubview:self.m_progressInd];
    [self.m_progressInd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    [self.view addSubview:self.m_lblHint];
    [self.m_lblHint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_textVerifi.bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
}


- (void)sure {
    [self showLoading];
    dispatch_queue_t bind_user = dispatch_queue_create("bind_user", nil);
    dispatch_async(bind_user, ^{
        NSString * errMsg;
        NSInteger iret = [[[OpenApiService alloc]init]userBind:strSrv port:iPort appId:strAppId appSecret:strAppSecret phone:self.m_textPhone.text smscode:self.m_textVerifi.text errmsg:&errMsg];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideLoading];
            if (iret < 0)
            {
                if(nil != errMsg)
                {
                    self.m_lblHint.text = [NSString stringWithFormat:@"绑定失败[%@]",errMsg];
                }
                else
                {
                    self.m_lblHint.text = @"绑定超时，请重试";
                    self.m_lblHint.lineBreakMode = UIControlStateNormal;
                    self.m_lblHint.numberOfLines = 0;
                }
                return;
            }
            else
            {
                self.m_lblHint.text = @"绑定成功";
                __weak typeof(self)weakSelf = self;
                [ZTLCCameraUtil fetchToken:self.m_textPhone.text CompletionBlock:^(id returnValue) {
                    __strong typeof(weakSelf)strongSelf = weakSelf;
                    if (!strongSelf) {
                        return;
                    }
                    LCOpenSDK_Api *m_hc = [ZTLCCameraUtil loadhc:returnValue];
                    UIStoryboard *currentBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    QRCoderViewController *QRCoderVc = [currentBoard instantiateViewControllerWithIdentifier:@"QRCoderView"];
                    QRCoderVc.enterVcType = EnterScanControllerTypeAddNewCamera;
                    [QRCoderVc setInfo:m_hc token:returnValue phone:strongSelf.m_textPhone.text devView:strongSelf];
                    [strongSelf.navigationController pushViewController:QRCoderVc animated:YES];
                } WithFailureBlock:^(NSString *errMsg) {
                    __strong typeof(weakSelf)strongSelf = weakSelf;
                    if (!strongSelf) {
                        return;
                    }
                    strongSelf.m_lblHint.text = errMsg;
                }];
            }
        });
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark  - lazy loading

- (UIButton *)m_btnPhone
{
    if (!_m_btnPhone) {
        _m_btnPhone = [UIButton buttonWithType:UIButtonTypeCustom];
        _m_btnPhone.backgroundColor = [UIColor whiteColor];
       [_m_btnPhone setImage:[UIImage imageNamed:@"phoneicon"] forState:UIControlStateNormal];
    }
    return _m_btnPhone;
}

- (UITextField *)m_textPhone
{
    if (!_m_textPhone) {
    
        _m_textPhone = [[UITextField alloc]init];
        _m_textPhone.placeholder = @"请输入注册号的手机号码";
        _m_textPhone.backgroundColor = [UIColor whiteColor];
        _m_textPhone.keyboardType = UIKeyboardTypeNamePhonePad;
    }
    return _m_textPhone;
}
- (UITextField *)m_textVerifi
{
    if (!_m_textVerifi) {
        _m_textVerifi = [[UITextField alloc]init];
        _m_textVerifi.placeholder = @"请输入验证码";
        _m_textVerifi.backgroundColor = [UIColor whiteColor];
        _m_textVerifi.keyboardType = UIKeyboardTypeNamePhonePad;

    }
    return _m_textVerifi;
}

-(void)onSendSms:(id)sender
{
    NSString * errCode;
    NSString * errMsg;
    
    NSInteger iret = [[[OpenApiService alloc]init]userBindSms:strSrv port:iPort appId:strAppId appSecret: strAppSecret phone:self.m_textPhone.text errcode:&errCode errmsg:&errMsg];
    if (iret < 0)
    {
        if (nil == errCode || 0 == errCode.length)
        {
            self.m_lblHint.text = @"发送验证码失败";
           debugLogInfo(@"发送验证码失败");
            
        }
        else
        {
            self.m_lblHint.text = [NSString stringWithString:errMsg];
           debugLogInfo(@"errMsg");
        }
        return;
    }
    
    self.m_lblHint.text = [NSString stringWithFormat:@"验证码短信已发送至手机%@",self.m_textPhone.text];
    
   debugLogInfo(@"验证码短信已发送至手机%@",self.m_textPhone.text);
    self.m_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onSmsTimer:) userInfo:self repeats:YES];
    self.m_interval = 60;
    self.m_btnSms.enabled = NO;
    
}

-(void) onSmsTimer:(id)sender
{
    self.m_interval --;
    NSLog(@"onSmsTimer-----[%ld]",(long)self.m_interval);
    [self.m_btnSms setTitle:[NSString stringWithFormat:@"重新获取(%ld)",(long)self.m_interval] forState:UIControlStateNormal];
    [self.m_btnSms setTitleColor:self.m_btnChangeColor forState:UIControlStateNormal];
    if (0 >= self.m_interval)
    {
        [self.m_timer invalidate];
        self.m_interval = 60;
        [self.m_btnSms setTitle:[NSString stringWithFormat:@"重新获取"] forState:UIControlStateNormal];
        [self.m_btnSms setTitleColor:self.m_btnOldColor forState:UIControlStateNormal];
        self.m_btnSms.enabled = YES;
    }

}
-(void)onBindUser:(id)sender
{
    [self showLoading];
    dispatch_queue_t bind_user = dispatch_queue_create("bind_user", nil);
    dispatch_async(bind_user, ^{
        NSString * errMsg;
        NSInteger iret = [[[OpenApiService alloc]init]userBind:strSrv port:iPort appId:strAppId appSecret:strAppSecret phone:self.m_textPhone.text smscode:self.m_textVerifi.text errmsg:&errMsg];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideLoading];
            if (iret < 0)
            {
                if(nil != errMsg)
                {
                    self.m_lblHint.text = [NSString stringWithFormat:@"绑定失败[%@]",errMsg];
                }
                else
                {
                    self.m_lblHint.text = @"绑定超时，请重试";
                    self.m_lblHint.lineBreakMode = UIControlStateNormal;
                    self.m_lblHint.numberOfLines = 0;
                }
                return;
            }
            else
            {
                self.m_lblHint.text = @"绑定成功";
                [self.navigationController popViewControllerAnimated:NO];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        });
    });
    
}


// 显示滚动轮指示器
-(void)showLoading
{
    [self.m_progressInd startAnimating];
}
// 消除滚动轮指示器
-(void)hideLoading
{
    if ([self.m_progressInd isAnimating])
    {
        [self.m_progressInd stopAnimating];
    }
}

#pragma mark - lazy loading
- (UIButton *)m_btnSms
{
    if (!_m_btnSms) {
        _m_btnSms = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnSms setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_m_btnSms setTitleColor:RGBColor(102, 102, 102) forState:UIControlStateNormal];
        _m_btnSms.titleLabel.font = [UIFont systemFontOfSize:13];
        [_m_btnSms setBackgroundColor:[UIColor whiteColor]];
        [_m_btnSms addTarget:self action:@selector(onSendSms:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnSms;
}

- (UIView *)m_viewVerifi
{
    if (!_m_viewVerifi) {
        _m_viewVerifi = [[UIView alloc]init];
        _m_viewVerifi.backgroundColor = [UIColor whiteColor];
    }
    return _m_viewVerifi;
}

- (UIView *)m_viewPhone
{
    if (!_m_viewPhone) {
        _m_viewPhone = [[UIView alloc]init];
        _m_viewPhone.backgroundColor = [UIColor whiteColor];
    }
    return _m_viewPhone;
}

- (UILabel *)m_lblHint
{
    if (!_m_lblHint) {
        _m_lblHint = [[UILabel alloc]init];
        _m_lblHint.textColor = self.m_btnChangeColor;
        _m_lblHint.font = [UIFont systemFontOfSize:13];
        _m_lblHint.textAlignment = NSTextAlignmentCenter;
    }
    return _m_lblHint;
}
- (UIActivityIndicatorView *)m_progressInd
{
    if (!_m_progressInd) {
        _m_progressInd = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _m_progressInd.transform = CGAffineTransformMakeScale(2.0, 2.0);
    }
    return _m_progressInd;
}
@end
